from typing import Dict, Any, List
from protocol.types import DataType


def _err(path: List[str], msg: str) -> ValueError:
    """统一的错误处理函数"""
    return ValueError(f"{'/'.join(path)}: {msg}")


def _ensure_int(value: Any, path: List[str]) -> int:
    """统一的整数转换函数，支持十进制与带 0x 前缀的十六进制字符串"""
    try:
        if isinstance(value, int):
            return value
        if isinstance(value, str):
            return int(value, 0)  # base=0 自动按前缀解析（如 0x..）
        return int(value)
    except Exception:
        raise _err(path, f"需要整数(支持0x前缀)，实际: {value}")


def _evaluate_simple_condition(condition: str, context: Dict[str, Any]) -> bool:
    """简单的条件求值函数，支持 == 和 != 操作符"""
    try:
        condition = condition.strip()
        if '!=' in condition:
            left, right = condition.split('!=', 1)
            left_val = int(context.get(left.strip(), 0))
            right_val = int(right.strip())
            return left_val != right_val
        elif '==' in condition:
            left, right = condition.split('==', 1)
            left_val = int(context.get(left.strip(), 0))
            right_val = int(right.strip())
            return left_val == right_val
        else:
            # 默认按布尔值处理
            return bool(int(condition.strip()))
    except Exception:
        # 条件求值失败时，默认包含该字段
        return True


def _evaluate_condition(condition: str, context: Dict[str, Any]) -> bool:
    """增强的条件求值函数，支持逻辑操作符"""
    try:
        condition = condition.strip()
        
        # 处理逻辑或
        if ' || ' in condition:
            conditions = condition.split(' || ')
            return any(_evaluate_simple_condition(cond.strip(), context) for cond in conditions)
        
        # 处理逻辑与
        elif ' && ' in condition:
            conditions = condition.split(' && ')
            return all(_evaluate_simple_condition(cond.strip(), context) for cond in conditions)
        
        # 简单条件
        else:
            return _evaluate_simple_condition(condition, context)
            
    except Exception:
        # 条件求值失败时，默认包含该字段
        return True


def _apply_field_modifications(field_cfg: Dict[str, Any], path: List[str], **params) -> Dict[str, Any]:
    """应用字段修改：mark标记和顶层模拟器"""
    result_cfg = field_cfg.copy()

    # 检查是否有mark标记
    mark = result_cfg.get('mark')
    if mark:
        if mark == 'sim':
            if 'sim' not in params:
                raise _err(path, f"字段标记为'sim'但未提供sim参数")
            result_cfg['value'] = params['sim']
        else:
            # 扩展性：支持其他标记类型
            if mark not in params:
                raise _err(path, f"字段标记为'{mark}'但未提供{mark}参数")
            result_cfg['value'] = params[mark]

    # 检查顶层模拟器值（新逻辑）
    simulator_values = params.get('simulator_values', {})
    if simulator_values:
        # 构建当前字段的路径（如 "body.time"）
        field_path = '.'.join(path)
        if field_path in simulator_values:
            result_cfg['value'] = simulator_values[field_path]

    return result_cfg
